package com.temp.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.temp.dto.CreateOrderDTO;
import com.temp.dto.SearchPaymentDTO;
import com.temp.entity.Campaign;
import com.temp.entity.PaymentOrder;
import com.temp.entity.User;
import com.temp.enumeration.PayType;
import com.temp.exception.BaseException;
import com.temp.result.Result;
import com.temp.service.CampaignService;
import com.temp.service.PaymentOrderService;
import com.temp.service.SystemSettingService;
import com.temp.service.impl.EpusdtService;
import com.temp.utils.EpusdtSignUtil;
import com.temp.utils.ShiroUtils;
import com.temp.utils.StringUtils;
import com.temp.vo.CustomPageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/payment")
@Api(tags = "支付相关接口")
@Validated
public class PaymentController {

    @Autowired
    private EpusdtService epusdtService;

    @Autowired
    private PaymentOrderService paymentOrderService;

    @Autowired
    private CampaignService campaignService;

    @Autowired
    private SystemSettingService settingService;

    /**
     * 创建支付订单
     */
    @PostMapping("/create")
    @ApiOperation("调用第三方支付插件接口")
    @RequiresPermissions("payment:payment:create")
    public Result createOrder(@Valid @RequestBody CreateOrderDTO request) {
        User user = ShiroUtils.getUser();
        SearchPaymentDTO searchPaymentDTO = new SearchPaymentDTO();
        searchPaymentDTO.setStatus(0);
        searchPaymentDTO.setPage(0);
        searchPaymentDTO.setUserId(user.getId());
        searchPaymentDTO.setPageSize(0);
        searchPaymentDTO.formatParam();

        if(PayType.USDT_TRC20.equals(request.getPayType())) {
            BigDecimal amount = request.getAmount();
            JSONObject jsonObject = JSONObject.parseObject(request.getExtParam());
            String campaignId = jsonObject.getString("campaignId");
            Campaign byId = campaignService.getById(campaignId);
            if(user.getId().equals(byId.getUserId())) {
                throw new BaseException("apiMsg.errorDonation");
            }
            if(!(amount.compareTo(BigDecimal.ZERO) > 0)) {
                throw new BaseException("apiMsg.amountMin,0");
            }
            searchPaymentDTO.setPayType(PayType.USDT_TRC20.getKey());
        }

        if(PayType.TRX.equals(request.getPayType())) {
            BigDecimal amount = request.getAmount();
            BigDecimal min_trx_num = settingService.getSettingValue("min_trx_num", BigDecimal.class).orElse(new BigDecimal("20"));
            if(amount.compareTo(min_trx_num) < 0) {
                throw new BaseException("apiMsg.TrxAmountMin," + min_trx_num);
            }
            searchPaymentDTO.setPayType(PayType.TRX.getKey());
        }
        CustomPageVO<PaymentOrder> paymentOrderCustomPageVO = paymentOrderService.queryAllPaymentOrder(searchPaymentDTO);
        if(paymentOrderCustomPageVO.getTotal() > 0) {
            throw new BaseException("apiMsg.waitOrder");
        }
        try {
            // 1. 创建本地订单
            PaymentOrder order = new PaymentOrder();
            order.setOrderId(EpusdtSignUtil.generateOrderId());
            order.setAmount(request.getAmount());
            order.setActualAmount(request.getAmount());
            order.setNotifyUrl(request.getNotifyUrl());
            order.setRedirectUrl(request.getRedirectUrl());
            order.setSubject(request.getSubject());
            order.setExtParam(request.getExtParam());
            order.setUserId(user.getId());
            order.setCurrencyName(request.getPayType().getKey());
            order.setCreateTime(LocalDateTime.now());

            // 2. 调用TokenPay创建支付订单
            PaymentOrder result = epusdtService.createPaymentOrder(order);

            return Result.success(result, "apiMsg.optionSuccess");
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return Result.error("apiMsg.createOrderError");
        }
    }

    /**
     * EPUSDT支付回调
     */
    @PostMapping("/notify")
    @ApiOperation("支付插件回调接口")
    public String epusdtNotify(@RequestBody JSONObject notifyData, HttpServletRequest request) {
        String clientIp = getClientIp(request);
        return epusdtService.handlePaymentNotify(notifyData, clientIp);
    }

    /**
     * 查询订单状态
     */
    @GetMapping("/status/{orderId}")
    @ApiOperation("查询订单状态接口")
    @RequiresPermissions("payment:payment:status")
    public Result getOrderStatus(@PathVariable String orderId) {
        PaymentOrder order = epusdtService.queryOrderStatus(orderId);
        if (order == null) {
            return Result.error("apiMsg.queryError");
        }
        return Result.success(order,"apiMsg.querySuccess");
    }

    @PostMapping("/query")
    @ApiOperation("查询订单信息")
    @RequiresPermissions("payment:payment:query")
    public Result getOrderByStatus(@RequestBody SearchPaymentDTO paymentDTO) {
        User user = ShiroUtils.getUser();
        paymentDTO.formatParam();
        paymentDTO.setUserId(user.getId());
        return Result.success(paymentOrderService.queryAllPaymentOrder(paymentDTO), "apiMsg.querySuccess");
    }

    private String getClientIp(HttpServletRequest request) {
        // 从请求头中获取真实IP（考虑代理情况）
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
